
package com.enlorenz.core.channel.socket.common.reader;

import com.enlorenz.common.util.MessageBuffer;

/**
 * 带长度的格式的报文读取类器
 * @author lcb
 */
public abstract class AbstractLengthBodyReader implements IReader {
	//头长度
	protected Integer headLength=8;
	//字符编码
	protected String code="UTF-8";
	//是否截除长度串
	protected boolean trimLength=true;
	//默认读取的长度
	protected int defaultReadLength=1024;
	
	
	public void setTrimLength(boolean trimLength) {
		this.trimLength = trimLength;
	}
	
	public void setCode(String code) {
		this.code = code;
	}

	public void setHeadLength(Integer headLength) {
		this.headLength = headLength;
	}
	
	/**
	 * 读取指定的长度
	 * @param length
	 * @return
	 */
	protected abstract byte [] readLength(int length) throws Exception;
	
	/**
	 * 获取整个长度
	 * @param headBuff 头长度BUFF
	 * @return 长度数字
	 * @throws Exception
	 */
	protected Integer getTotalLen(byte[] headBuff) throws Exception{
		//全长
		Integer totalLen=Integer.parseInt(new String(headBuff, 0, headLength, code).trim());
		return totalLen;
	}
	
	@Override
	public byte[] read() throws Exception {
		MessageBuffer messageBuffer = new MessageBuffer();
		//读取消息头
		byte[] headBuff=readLength(headLength);
		if(!trimLength){
			messageBuffer.append(headBuff);
		}
		
		//全长
		Integer totalLen=getTotalLen(headBuff);
		//已经读取
		int alreadyReaded=0;
		
		while(alreadyReaded<totalLen){
			
			int leftReaded=totalLen-alreadyReaded;
			int needReaded=defaultReadLength;
			if(leftReaded<defaultReadLength){
				needReaded=leftReaded;
			}
			
			byte [] real=readLength(needReaded);
			if(null == real){
				break;
			}
			alreadyReaded+=real.length;
			messageBuffer.append(real);
		}
		
		return messageBuffer.toByte();
	}

	
}
